<template>
  <div>
    <!-- 新增或修改对话框 -->
    <el-dialog
      :title="modelEntity.title"
      :close-on-click-modal="false"
      v-model="modelEntity.open"
      width="1100px"
      append-to-body
    >
      <el-form ref="formRef" :model="modelEntity.data" :rules="modelEntity.rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="参数名称" prop="entityName">
              <el-input
                v-model="modelEntity.data.entityName"
                placeholder="请输入参数名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数类型" prop="entityClass">
              <el-select v-model="modelEntity.data.entityClass" style="width: 100%" :disabled="true">
                <el-option
                  v-for="item in entityClassOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            <!--            <el-input v-model="modelEntity.data.entityClass" placeholder="请输入参数类型" clearable/>-->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数描述" prop="entityDesc">
              <el-input
                v-model="modelEntity.data.entityDesc"
                placeholder="请输入参数描述"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-button
              size="mini"
              icon="el-icon-plus"
              type="primary"
              style="margin-left: 5px"
              @click="addAttribute"
            >添加
            </el-button>
            <el-button
              size="mini"
              icon="el-icon-plus"
              type="primary"
              style="margin-left: 5px"
              @click="importAttribute"
            >从已有数据源导入
            </el-button>
            <el-table
              class="config-table addmodel-table"
              :data="attrList"
              border
              stripe
              fit
              highlight-current-row
              :header-cell-style="{ background: '#f6f7fa', 'margin-top': '5px', width: '50%' }"
              style="width: 100%; margin-top: 10px"
              max-height="600px"
            >
              <el-table-column
                label="子参数名称"
                align="center"
                prop="entityName"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <div>
                    <span style="color: red"> * </span>
                    <el-input v-model="scope.row.entityName" clearable />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="子参数类型"
                align="center"
                prop="entityClass"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <div>
                    <span style="color: red"> * </span>
                    <el-select v-model="scope.row.entityClass" style="width: 100%">
                      <el-option
                        v-for="item in entityClassOptions"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      />
                    </el-select>
                  <!--                <el-input v-model="scope.row.entityClass" clearable />-->
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="子参数描述"
                align="center"
                prop="entityDesc"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <el-input v-model="scope.row.entityDesc" clearable />
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center" width="80">
                <template #default="{ $index }">
                  <span
                    @click="removeAttribute($index)"
                    style="color: red; margin-left: 5px; cursor: pointer"
                  >
                    删除
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <dialog-footer @ok="submitForm" @cancel="cancel" style="margin: 30px 0 0" />
    </el-dialog>

    <!-- 新增或修改对话框 -->
    <el-dialog
      v-el-drag-dialog :title="editForm.title" :close-on-click-modal="false" v-model="editForm.open"
      width="50%" append-to-body>
      <el-form ref="dataSourceFormRef" :model="editForm.data" :rules="editForm.rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="数据源" prop="datasourceCode">
              <el-select v-model="editForm.data.datasourceCode" placeholder="请选择数据源" @change="getModelColumn" :disabled="editForm.isModify">
                <el-option
                  v-for="(op, index) in dataSourceOptions" :key="index" :label="op.datasourceCode"
                  :value="op.datasourceCode" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="数据源实体" prop="tableName"
              v-if="editForm.data.datasourceCode" required>
              <el-select-v2 v-model="editForm.data.tableName" placeholder="请选择数据源实体" :disabled="editForm.isModify" :options="formEntityList" :props="{label: 'dictValue', value: 'dictValue'}" filterable>
              </el-select-v2>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitDataSourceForm" @cancel="cancelDataSource" />
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { debounceWrapper } from '@/utils/zmids.ts'
import { insert, insertModelEntity, updateById,getAttributeList,getTableList } from '@/platform/uni/api/uni/domain/index.ts'
import { getDatasource } from "@uni/api/uni/mda/table/info"

export default {
  name: 'AddModelEntity',
  props: ['modelEntityForm', 'entityClassOptions'],
  data() {
    return {
      modelEntity: {},
       // 数据源选择列表
      dataSourceOptions: [],
      // 实体列表
      formEntityList: [],
      editForm: {
        // 控制 dialog
        open: false,
        // 弹出层标题
        title: '',
        // 是否修改操作
        isModify: false,
        // 表单参数
        data: {},
        // 规则
        rules: {
          // 数据源
          datasourceCode: [
            { required: true, message: '数据源不可以为空', trigger: 'blur' }
            , { min: 1, max: 64, message: "数据源的长度最多 64 个字符", trigger: "blur" }
          ],
          // 表名
          tableName: [
            { required: true, message: '表名不可以为空', trigger: 'blur' }
            , { min: 1, max: 64, message: "表名的长度最多 64 个字符", trigger: "blur" }
          ],
        },
      }
    }
  },
  computed: {
    attrList: {
      get() {
        const form = this.modelEntity?.data || {}
        return form['attrList'] || []
      },
      set(v) {
        this.modelEntity.data['attrList'] = v
      }
    }
  },
  mounted() {
    this.modelEntity = this.modelEntityForm
  },
  methods: {
    // 确定按钮
    submitDataSourceForm: debounceWrapper(function () {
      // this.modelEntity.data.isObject = 'Y';
      this.$refs['dataSourceFormRef'].validate((valid) => {
        if (valid) {
          const params = {
            datasourceCode: this.editForm.data.datasourceCode,
            tableName: this.editForm.data.tableName
          }
          getAttributeList(params).then(response => {
            this.modelEntity.data.entityName = response.data.entityName;
            this.modelEntity.data.entityClass = response.data.entityClass;
            this.modelEntity.data.entityDesc = response.data.entityDesc;
            this.attrList = response.data.attrList;
          })
          this.editForm.open = false
        }
      })
    }),
    // 提交按钮
    submitForm: debounceWrapper(function () {
      // this.modelEntity.data.isObject = 'Y';
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          if (this.modelEntity.data['attrList']?.length > 0) {
            let checkResult = this.modelEntity.data['attrList'].every((e) => {
              var regExp = /^[a-zA-Z][a-zA-Z0-9_]*$/
              console.log(e.entityName)
              console.log(e.entityClass)
              console.log(regExp.test(e.entityName))
              console.log(regExp.test(e.entityClass))
              return (
                e.entityName &&
                e.entityClass &&
                regExp.test(e.entityName) &&
                regExp.test(e.entityClass)
              )
            })
            if (!checkResult) {
              this.$message.error('属性配置有误，无法保存！')
              return
            }
          } else {
            this.$message.error('属性配置有误，请填写完整！')
            return
          }

          insertModelEntity(this.modelEntity.data).then((response) => {
            this.msgSuccess('新增成功')
            this.modelEntity.open = false
            this.$emit('getList')
          })
        }
      })
    }),
    // 取消按钮
    cancel() {
      this.modelEntity.open = false;
    },
    cancelDataSource() {
      this.editForm.open = false
    },
    addAttribute() {
      this.attrList.push({})
    },
    importAttribute() {
      this.resetDataSourceForm();
      this.editForm.open = true;
      this.editForm.title = "选择数据表";
      // 获取数据源选择列表
      this.getDataSourceOptions();
    },
    //数据源选择 选择建模-现有模板 - 下拉框
    getDataSourceOptions() {
      getDatasource().then(response => {
        console.log('response.data', response.data)
        this.dataSourceOptions = response.data
      })
    },
    // 获取实体
    getModelColumn(){
      if (this.editForm.data.datasourceCode != undefined) {
        const params = {
            datasourceCode: this.editForm.data.datasourceCode
          }
        getTableList(params).then((response) => {
          this.formEntityList = response.data
        })
      }
    },
    removeAttribute(i) {
      this.attrList.splice(i, 1)
    },
    resetCurrentForm() {
      // 重置字段校验
      this.$refs.formRef && this.$refs.formRef.clearValidate()
      this.resetForm('formRef')
      this.attrList = [];
    },
    resetDataSourceForm(){
      this.editForm.data = {
        // 主键ID
        tableId: undefined,
        // 数据源编码
        datasourceCode: undefined,
        // 表名
        tableName: '',
      };
      // 重置字段校验
      this.$refs.dataSourceFormRef && this.$refs.dataSourceFormRef.clearValidate();
      this.resetForm("dataSourceFormRef");
    }
  }
}
</script>

<style scoped lang="scss">
.addmodel-table {
  .el-radio {
    margin-right: 10px;
  }
}
</style>
